package com.rongshe.hotel.utils;

import com.alibaba.fastjson2.JSONObject;
import com.rongshe.common.exception.ServiceException;
import com.rongshe.common.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Key;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

// WxUtils.java
@Component
@Slf4j
public class WxUtils {
    @Value("${wx.appid}")
    private String appId;

    @Value("${wx.secret}")
    private String secret;

    /**
     * 获取微信session_key和openid
     */
    public JSONObject getSessionKey(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", secret);
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");

        String result = HttpUtils.sendGet(url, HttpUtils.mapToUrlParams(params));
        return JSONObject.parseObject(result);
    }

    /**
     * 解密手机号
     */
    public String decryptPhone(String sessionKey, String encryptedData, String iv) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(sessionKey);
            byte[] ivBytes = Base64.getDecoder().decode(iv);
            byte[] dataBytes = Base64.getDecoder().decode(encryptedData);

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            Key key = new SecretKeySpec(keyBytes, "AES");
            AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
            params.init(new IvParameterSpec(ivBytes));

            cipher.init(Cipher.DECRYPT_MODE, key, params);
            byte[] decrypted = cipher.doFinal(dataBytes);

            String json = new String(decrypted, StandardCharsets.UTF_8);
            JSONObject jsonObject = JSONObject.parseObject(json);
            return jsonObject.getString("phoneNumber");
        } catch (Exception e) {
            log.error("解密手机号失败", e);
            throw new ServiceException("解密手机号失败");
        }
    }
}
